package com.etrans.web.gps.business.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.system.domain.UserVO;
import com.etrans.web.gps.business.system.service.UserService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageResultVo;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.CsEncodeUtils;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.etrans.web.gps.util.grid.ParamMap;
import com.etrans.web.gps.util.grid.ParamValueObject;

/**
 * 用户管理
 * @author jw.chen
 *
 */
@Controller
@RequestMapping("/system/user/*")
public class UserController extends BaseController {

	private final static Logger log = LoggerFactory.getLogger("UserController");

	@Autowired
	private UserService userService;
	
	//加载用户列表
	@RequestMapping(value = "listUsers.html")
	public ModelAndView listUsers(HttpServletRequest request, Model model) {
		ModelAndView mnv = new ModelAndView();
		mnv.setViewName("views/business/system/user/queryUser");
		return mnv;
	}
	
	//查询所有用户
	@RequestMapping(value="loadAllUsers.html")
	public void loadAllUsers(HttpServletResponse response,HttpServletRequest request,String paramsGrid){
		try {	
			ParamMap param = FlexiGridUtil.parseJSONParam(paramsGrid);
			ParamValueObject inputParam = this.parseJSONParam(param);
			HashMap<String, Object> params=inputParam.getMapParams();
			List<UserVO> rows = userService.queryAllUsers(params);
			Long total = userService.allUsersCount(params);
			
			PageVo pageBean = new PageVo();
			pageBean.setRows(rows);
			pageBean.setPage(inputParam.getFromNumber());
			pageBean.setTotal(total.intValue());
			
			ajaxResultJson(response,pageBean);
		} catch (Exception e) {
			log.error("加载用户失败", e);
			e.printStackTrace();
		}
	}

	//新增用户
	@RequestMapping(value = "initUser.html")
	public ModelAndView initUser() {
		ModelAndView mav = new ModelAndView();
		UserVO user= new UserVO();
		mav.addObject("addUser",user);
		mav.setViewName("views/business/system/user/addUserForm");
		return mav;
	}

	
	//加载用户信息
	@RequestMapping(value = "loadUserById.html")
	public ModelAndView loadUserById(HttpServletRequest request, int userId) {
		ModelAndView mav = new ModelAndView();
		try {
			UserVO user = userService.queryUserByUserId(userId);
			mav.addObject("addUser", user);
			mav.setViewName("views/business/system/user/addUserForm");
		} catch (Exception e) {
			log.error("获取用户信息失败", e);
		}
		return mav;
	}
	
	//保存用户信息
	@RequestMapping(value = "saveUser.html")
	public void saveUser(HttpServletRequest request,HttpServletResponse response, UserVO user) {
		PageResultVo pr = new PageResultVo();
		try {
			int userCount=userService.userNameCount(user);
			if(userCount==0){
				user.setUpdate_time(new Date());
				user.setEnable(true);
				user.setSuper_admin(false);
				//	2017-09-20  	add 开始 
				// 默认密码123456 
				String _src = "123456";
				String login_pwd = CsEncodeUtils.Encrypt(_src);
				user.setLogin_pwd(login_pwd);
				//	2017-09-20  	add 结束
				userService.saveUser(user);
				pr.setCode(Constant.RETURN_OK_CODE);
			}else{
				pr.setCode(Constant.RETURN_Repent_CODE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("保存失败!");
		}
		ajaxResultJson(response, pr);
	}
	
	//保存用户信息
	@RequestMapping(value = "updateUser.html")
	public void updateUser(HttpServletRequest request,HttpServletResponse response, UserVO user) {
		PageResultVo pr = new PageResultVo();
		try {
			int userCount=userService.userNameCount(user);
			if(userCount==0){
				user.setUpdate_time(new Date());
				userService.updateUser(user);
				pr.setCode(Constant.RETURN_OK_CODE);
			}else{
				pr.setCode(Constant.RETURN_Repent_CODE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("保存失败!");
		}
		ajaxResultJson(response, pr);
	}

	//删除用户信息
	@RequestMapping(value="deleteUser.html")
	public void deleteUser(HttpServletResponse response,String userIds){
		PageResultVo pr = new PageResultVo();
		try {
			userIds=userIds.replaceAll("row", "");
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				for (String s : userId) {
					userService.deleteUser(Integer.parseInt(s));
				}
			}
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("删除失败!");
		}
		
		ajaxResultJson(response, pr);
	}
	
	//重置用户密码
	@RequestMapping(value="resetPassword.html")
	public void resetPassword(HttpServletResponse response,String userIds){
		PageResultVo pr = new PageResultVo();
		try {
			userIds=userIds.replaceAll("row", "");
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				for (String s : userId) {
					HashMap<String,Object> param = new HashMap<String, Object>();
					param.put("userId", s);
					param.put("login_pwd", CsEncodeUtils.Encrypt("888888"));
					userService.updatePassword(param);
				}
			}
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("重置失败!");
		}
		ajaxResultJson(response, pr);
	}
		
	/**
	 * 验证username是否存在
	 */
	@RequestMapping(value="isExistUser.html")
	public void isExistUser(HttpServletResponse response,String id,String userName){
		HashMap<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("id", id);
		paramsMap.put("userName", userName);
		try {
			ajaxResultJson(response,userService.queryByUserName(paramsMap) == null);
		} catch (Exception e) {
			log.error("check username[" + userName + "] exist happed error",e);
			ajaxResultJson(response, false);
		}
	}
}
